import json

from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt

from message_management.models import Message
from .models import Room
from django.utils.dateparse import parse_datetime


def get_all_messages(request):
    data = json.loads(request.body.decode('utf-8'))  # 确保使用正确的编码
    rooms = Room.objects.filter(user_id=data['user_id'], status=1).order_by('-update_time')
    # 查询所有数据
    # rooms = Room.objects.all()
    return JsonResponse([room.serialize() for room in rooms], safe=False, status=200)


def delete_room(request):
    data = json.loads(request.body.decode('utf-8'))  # 确保使用正确的编码

    room_type = data.get('type')
    room_id = data.get('room_id')
    user_id = data.get('user_id')

    if room_type == "clear":
        Message.objects.filter(room_id=room_id).delete()
    elif room_type == "del":
        Room.objects.filter(id=room_id).update(status=0)
    elif room_type == "delAll":
        Room.objects.filter(user_id=user_id).update(status=0)

    return JsonResponse({'message': 'success'}, status=200)
